#define _CRT_SECURE_NO_WARNINGS 1
#include"SListNode.h"

SLNode* SLNBuyNode(SLNodeDataType x)
{
	SLNode* node = (SLNode*)malloc(sizeof(SLNode));
	if (node == NULL)
	{
		perror("malloc failed!");
		exit(1);
	}
	node->data = x;
	node->next = NULL;
	return node;
}
void SLNodePrint(SLNode* phead)
{
	SLNode* pcur = phead;
	while (pcur)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}
void SLNPushBack(SLNode** pphead, SLNodeDataType x)
{
	assert(pphead);
	SLNode* newnode = SLNBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SLNode* ptail = *pphead;
		while (ptail->next)
		{
			ptail = ptail->next;
		}
		ptail->next = newnode;
	}
}
void SLNPushFront(SLNode** pphead, SLNodeDataType x)
{
	assert(pphead);
	SLNode* newnode = SLNBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		newnode->next = *pphead;
		*pphead = newnode;
	}
}
void SLNPopBack(SLNode** pphead)
{
	assert(pphead && *pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLNode* ptail = *pphead;
		SLNode* prev = NULL;
		while (ptail->next)
		{
			prev = ptail;
			ptail = ptail->next;
		}
		free(ptail);
		ptail = NULL;
		prev->next = NULL;
	}
}
void SLNPopFront(SLNode** pphead)
{
	assert(pphead && *pphead);
	SLNode* Next = (*pphead)->next;
	free(*pphead);
	*pphead = Next;
}
SLNode* SLNodeFind(SLNode* phead, SLNodeDataType x)
{
	assert(phead);
	SLNode* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
void SLNodeInsert(SLNode** pphead, SLNode* pos, SLNodeDataType x)
{
	assert(pphead && *pphead);
	assert(pos);
	SLNode* newnode = SLNBuyNode(x);
	if (*pphead == pos)
	{
		newnode->next = *pphead;
		*pphead = newnode;
	}
	else
	{
		SLNode* pcur = *pphead;
		while (pcur->next != pos)
		{
			pcur = pcur->next;
		}
		newnode->next = pos;
		pcur->next = newnode;
	}
}
void SLNodeInsertAfter(SLNode* pos, SLNodeDataType x)
{
	assert(pos);
	//pos newnode pos->next
	SLNode* newnode = SLNBuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}
void SLNodeErase(SLNode** pphead, SLNode* pos)
{
	assert(pphead && *pphead);
	assert(pos);
	if (*pphead == pos)
	{
		SLNode* Next = (*pphead)->next;
		free(*pphead);
		*pphead = Next;
		pos = NULL;
	}
	else
	{
		SLNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
void SLNodeEraseAfter(SLNode* pos)
{
	assert(pos && pos->next);
	SLNode* del = pos->next;
	pos->next = pos->next->next;
	free(del);
	del = NULL;
}
void SLNodeDestroy(SLNode** pphead)
{
	assert(pphead && *pphead);
	SLNode* pcur = *pphead;
	while (pcur)
	{
		SLNode* Next = pcur->next;
		free(pcur);
		pcur = Next;
	}
	*pphead = NULL;
}